package dao.impl;

import bean.dto.Login;
import bean.dto.UserRoleDTO;
import bean.dto.UserRoleQueryPage;
import bean.pojo.Permissions;
import bean.pojo.User;
import bean.vo.UserRoleVo;
import bean.vo.UserVo;
import commons.dbHelper.DBHelper;
import commons.jdbc.basic.JDBCUtil;
import dao.UserDao;
import dao.UserRoleDao;

import java.util.*;

/**
 * dao.impl
 * User: mcw
 * Date: 2024/12/16 上午10:09
 * motto:   春天（spring）没有虫子（bug)
 * Description:
 * Version: V1.0
 */
public class UserRoleDaoImpl implements UserRoleDao {


    @Override
    public List<UserRoleVo> findByPage(UserRoleQueryPage queryPage) {
        //sql
        StringBuffer sql = new StringBuffer("select u.*,r.role_name from user u left join user_roles ur on u.user_id=ur.user_id left join roles r on r.role_id=ur.role_id where 1=1 ");
        //集合参数
        List<Object> parameters = new ArrayList<>();
        //验证是否为空  null  "    "
        if (queryPage.getRoleId() != null) {
            parameters.add(queryPage.getRoleId());
            sql.append(" and  r.role_id =? ");
        }
        if (queryPage.getUserName() != null) {
            parameters.add(queryPage.getUserName());
            sql.append(" and  u.user_name like concat('%',?,'%') ");
        }
        sql.append("  order by  u.user_id ");
        sql.append("  limit  " + ((queryPage.getPage() - 1) * queryPage.getLimit())
                + "," + queryPage.getLimit());
        System.out.println("sql:" + sql);
        System.out.println("参数:" + parameters);
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql.toString(), parameters.toArray());
        System.out.println(Arrays.toString(query.toArray()));
        if (query.size() > 0) {
            List<UserRoleVo> list = new ArrayList<>();
            for (Map<String, Object> row : query) {//Community
                UserRoleVo vo = new UserRoleVo();
                vo.setUserId((Integer) row.get("user_id"));
                vo.setUserName((String) row.get("user_name"));
                vo.setUserPhone((String) row.get("user_phone"));
                vo.setRoleName((String) row.get("role_name"));
                vo.setPassword((String) row.get("password"));
                list.add(vo);
            }
            System.out.println("List<UserRoleVo>:list:" + list);
            return list;
        }
        return null;
    }

    @Override
    public Long findByTotal(UserRoleQueryPage queryPage) {
        //sql
        StringBuffer sql = new StringBuffer("select  count(*) ct  from  user u left join user_roles ur on u.user_id=ur.user_id where  1=1 ");
        //集合参数
        List<Object> parameters = new ArrayList<>();
        //验证是否为空  null  "    "
        if (queryPage.getRoleId() != null) {
            parameters.add(queryPage.getRoleId());
            sql.append(" and  ur.role_id =? ");
        }
        if (queryPage.getUserName() != null) {
            parameters.add(queryPage.getUserName());
            sql.append(" and  u.user_name like concat('%',?,'%') ");
        }
        System.out.println("sql:" + sql);
        System.out.println("参数:" + parameters);
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql.toString(), parameters.toArray());
        //默认0条
        Long ct = 0L;
        if (query.size() > 0) {
            //该变
            ct = (Long) query.get(0).get("ct");
        }
        return ct;
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public boolean deleteUserRole(Integer userId) {
        String sql = "delete from user where user_id=?";
        String sql1="delete from user_roles where user_id=?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        int update = jdbcUtil.update(sql, userId);
        if (update > 0) {
            //查询用户是否有角色
            String sql2="select * from user_roles where user_id=?";
            List<Map<String, Object>> query = jdbcUtil.query(sql2, userId);
            if (query.size() > 0) {
                //有角色则删除该用户的角色
                int update1 = jdbcUtil.update(sql1, userId);
                return update == update1;
            }
        }
        return update > 0;
    }

    @Override
    public boolean insert(UserRoleDTO userRoleDTO) {
        String sql1 = "insert into user(user_name,user_phone,password) values(?,?,?)";
        String userName = userRoleDTO.getUserName();
        String phone = userRoleDTO.getUserPhone();
        String password = userRoleDTO.getPassword();
        Integer roleId = userRoleDTO.getRoleId();
        JDBCUtil jdbcUtil = new JDBCUtil();
        int update = jdbcUtil.update(sql1, userName, phone, password);
        if (update > 0) {
            //判断是否要为用户绑定角色
            if (roleId != null) {
                //查询插入的用户id
                String sql2 = "select user_id from user where password=? and user_name=? and user_phone=?";
                List<Map<String, Object>> query = jdbcUtil.query(sql2, password, userName, phone);
                Integer id = (Integer) query.get(0).get("user_id");
                //为用户绑定角色
                String sql3 = "insert into user_roles(user_id,role_id) values(?,?)";
                int update1 = jdbcUtil.update(sql3, id, roleId);
                return update1 > 0;
            }
        }
        return update > 0;
    }

    /**
     * 修改用户用户角色
     *
     * @param userRoleDTO
     * @return
     */
    @Override
    public boolean updateUserRole(UserRoleDTO userRoleDTO) {
        String sql = "update user set user_name=?,user_phone=?,password=? where user_id=?";
        Integer userId = userRoleDTO.getUserId();
        String userName = userRoleDTO.getUserName();
        String phone = userRoleDTO.getUserPhone();
        String password = userRoleDTO.getPassword();
        Integer roleId = userRoleDTO.getRoleId();
        JDBCUtil jdbcUtil=new JDBCUtil();
        int update = jdbcUtil.update(sql, userName, phone, password, userId);
        if (update > 0) {
            //是否传入了角色id，角色id不为空则修改用户角色
            if (roleId != null) {
                //查询用户是否有角色
                String sql2="select role_id from user_roles where user_id=?";
                List<Map<String, Object>> query = jdbcUtil.query(sql2, userId);
                //用户有角色则直接更改角色
                if (query.size() > 0) {
                    String sql1="update user_roles set role_id=? where user_id=?";
                    int update1 = jdbcUtil.update(sql1, roleId, userId);
                    return update1 > 0;
                }
                //用户没有角色则直接直接插入
                String sql3="insert into user_roles(user_id,role_id) values(?,?)";
                int update2 = jdbcUtil.update(sql3, userId, roleId);
                return update2 > 0;
            }
        }
        return update > 0;
    }
}
